#include "ECS/PScene.h"
#include "ECS/PEntity.h"
#include "ECS/Component/PTransformComponent.h"

namespace Piccolo
{
    void PScene::OnInit()
    {
        mRootNode = std::make_unique<PNode>();
        mRootNode->SetName("ROOT");
    }

    void PScene::OnDestroy()
    {
        DestroyAllEntity();
        mEntities.clear();
        mRootNode.reset();
        mSystemList.clear();
    }

    PEntity* PScene::CreateEntity(const std::string &name)
    {
        return CreateEntityWithUUID(PUUID(), name);
    }

    PEntity* PScene::CreateEntityWithUUID(const PUUID &id, const std::string &name)
    {
        entt::entity e = mEcsRegistry.create();
        mEntities.insert({ e, std::make_shared<PEntity>(e, this) });
        mEntities[e]->SetParent(mRootNode.get());
        mEntities[e]->SetId(id);
        mEntities[e]->SetName(name.empty() ? "Entity" : name);
        // 默认都必须有基础组件TransformComponent
        mEntities[e]->AddComponent<PTransformComponent>();
        return mEntities[e].get();
    }

    void PScene::DestroyEntity(const PEntity *entity)
    {
        if (entity && entity->IsValid())
        {
            mEcsRegistry.destroy(entity->GetEcsEntity());
        }

        auto it = mEntities.find(entity->GetEcsEntity());
        if (it != mEntities.end())
        {
            PNode* parent = it->second->GetParent();
            if (parent)
            {
                parent->RemoveChild(it->second.get());
            }
            mEntities.erase(it);
        }
    }

    void PScene::DestroyAllEntity()
    {
        mEcsRegistry.clear();
        mEntities.clear();
    }

    PEntity * PScene::GetEntity(entt::entity enttEntity)
    {
        if (mEntities.find(enttEntity) != mEntities.end())
        {
            return mEntities.at(enttEntity).get();
        }
        return nullptr;
    }
}
